package xyz.xtgl.security.springboot.authentication.merchant;

import xyz.xtgl.security.springboot.entity.CustomUserDetails;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 认证服务器
 * @author liubo
 * @created 2019-12-14 11:58
 */
@Setter
public class MerchantAuthenticationProvider implements AuthenticationProvider {

    private MerchantUserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) {
        MerchantAuthenticationToken authenticationToken = (MerchantAuthenticationToken) authentication;
        String usernameOrPhone = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        //对应自定义的 CustomUserDetailsServiceImpl 中的实现方法
        CustomUserDetails user = userDetailsService.loadMerchantUserByUsernameOrPhone(usernameOrPhone);
        if (user == null) {
            throw new InternalAuthenticationServiceException("用户不存在");
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        MerchantAuthenticationToken authenticationResult = new MerchantAuthenticationToken(user, password, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MerchantAuthenticationToken.class.isAssignableFrom(authentication);
    }
}